# ！/usr/bin/env python
# -*- coding = utf-8 -*-
# ================================================
# @Time  :2021/8/5 17:32
# @Author:tyh
# @File  :testcase.py
# @Phone :13926528314
# ================================================
from flask import request
from flask_restful import Resource

from models.testcase import TestCase
from server import app, db


class TestCaseServer(Resource):
    """
    测试用例服务
    """
    # 方法名对应app.routez红的methods
    def get(self):
        case_id = request.args.get("id")
        if case_id:
            app.logger.info(f"查找用例id={id}")
            case_data = TestCase.query.filter_by(id=case_id).first()
            # data = [{"id": case_data.id, "nodeid": case_data.nodeid, "remark": case_data.remark}]
            data = [case_data.as_dict()]
        else:
            app.logger.info("查找所有用例")
            case_data = TestCase.query.all()
            # data = [{"id":i.id, "nodeid":i.nodeid, "remark":i.remark}for i in case_data]
            data = [i.as_dict() for i in case_data]
        return {"error": 0, "msg": {"data": data}}

    def post(self):
        case_data = request.json
        app.logger.info(f"插入用例case_data={case_data}")
        test_case = TestCase(**case_data)
        # test_case.nodeid = json.dumps(request.json.get("nodeid"))
        db.session.add(test_case)
        db.session.commit()
        db.session.close()
        return {"error": 0, "msg": "post success"}

    def put(self):
        case_id = request.json.get("id")
        case=TestCase.query.filter_by(id=case_id).update(request.json)
        app.logger.info(f"修改用例request.json={request.json}")
        db.session.commit()
        db.session.close()
        return {"error": 0, "msg": {"id":case}}

    def delete(self):
        case_id = request.args.get("id")
        app.logger.info(f"case_id:{case_id}")
        if case_id:
            case = TestCase.query.filter_by(id=case_id).delete()
            app.logger.info(f"删除用例case={case}")
            db.session.commit()
            db.session.close()
            return {"error": 0, "msg": "delete success"}
        else:
            app.logger.info("没有id，无法删除")
            return {"error": 40001, "msg": "delete case id not find"}

